package cn.maihe.elg.operation.utils;

import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMBaseRespDTO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {
    // 使用连接池（类成员变量）
    private static final CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);       // 最大连接数
        cm.setDefaultMaxPerRoute(50); // 每个路由最大连接数

        httpClient = HttpClientBuilder.create()
                .setConnectionManager(cm)
                .build();
    }

//    public static String doPostFormData(String httpUrl, Map<String, Object> param, String charset) {
//        // 创建httpPost
//        HttpPost httpPost = new HttpPost(httpUrl);
//        httpPost.addHeader("Connection", "");
////        httpPost.setHeader("Content-Type", "multipart/form-data; charset=UTF-8");
//        // 创建参数队列
//        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//        builder.setCharset(Charset.defaultCharset());
//        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//        builder.setContentType(ContentType.MULTIPART_FORM_DATA.withCharset(Charset.defaultCharset()));
//        param.forEach((k, v) -> {
//            if (v instanceof File) {
//                if (v != null) {
//                    log.info("文件推送：文件路径：{}", ((File) v).getPath());
//                }
//                FileBody fileBody = v != null ? new FileBody((File) v,
//                        ContentType.MULTIPART_FORM_DATA.withCharset(Charset.defaultCharset()), ((File) v).getName()) : null;
//                if (fileBody != null) {
//                    builder.addPart(k, fileBody);
//                }
//            } else {
//                builder.addTextBody(k, v.toString(), ContentType.TEXT_PLAIN.withCharset(Charset.defaultCharset()));
//            }
//        });
//        HttpEntity httpEntity = builder.build();
//        try {
//            httpPost.setEntity(httpEntity);
////            setHttpHeader(httpPost);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        String result = sendHttpPost(httpPost);
//        return result;
//    }

    private static String sendHttpPost(HttpPost httpPost) {
        try {
            // 设置超时（可根据需要调整）
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(30000)
                    .build();
            httpPost.setConfig(config);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            ElgLogger.error(log, l -> l.error("HTTP请求失败 URL: {}", httpPost.getURI(), e));
//            log.error("HTTP请求失败 URL: {}", httpPost.getURI(), e);
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    public static String doPostFormData(String httpUrl, Map<String, Object> params) {
        // 1. 创建 HttpPost 对象
        HttpPost httpPost = new HttpPost(httpUrl);
//        httpPost.setHeader("Content-Type", "multipart/form-data;charset=UTF-8");

        // 2. 构造 MultipartEntityBuilder
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(StandardCharsets.UTF_8); // 设置字符集为 UTF-8

//        // 3. 添加文本参数
//        builder.addTextBody("username", "张三", ContentType.TEXT_PLAIN.withCharset("UTF-8"));
//        builder.addTextBody("age", "25", ContentType.TEXT_PLAIN.withCharset("UTF-8"));
//
//        // 4. 添加文件（可选）
//        File file = new File("path/to/your/file.txt");
//        builder.addBinaryBody(
//                "file",
//                file,
//                ContentType.DEFAULT_BINARY,
//                file.getName()
//        );

        params.forEach((k, v) -> {
            if (v instanceof File) {
                if (v != null) {
                    ElgLogger.error(log, l -> log.info("文件推送：文件路径：{}", ((File) v).getPath()));
                    // 4. 添加文件（可选）
                    builder.addBinaryBody(
                            k,
                            (File) v,
                            ContentType.DEFAULT_BINARY,
                            ((File) v).getName()
                    );
                }
            } else {
                // 3. 添加文本参数
                builder.addTextBody(k, v.toString(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            }
        });

        // 5. 构建 HttpEntity 并设置到请求中
        HttpEntity httpEntity = builder.build();
        try {
            httpPost.setEntity(httpEntity);
        } catch (Exception e) {
            ElgLogger.error(log, l -> l.error("HttpPost构建失败 URL: {}", httpPost.getURI(), e));
//            log.error("HttpPost构建失败 URL: {}", httpPost.getURI(), e);
            throw new RuntimeException("HttpPost构建异常: " + e.getMessage(), e);
        }
        return sendHttpPost(httpPost);
    }

    public static String doPostFormUrlencoded(String httpUrl, Map<String, Object> params) {
        // 1. 创建 HttpPost 对象
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 2. 构造表单参数
        List<BasicNameValuePair> formParams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value != null) {
                if (value instanceof File) {
                    // 不支持文件上传（因为 application/x-www-form-urlencoded 不支持）
                    ElgLogger.error(log, l -> l.warn("警告：字段 {} 是文件类型，application/x-www-form-urlencoded 不支持文件上传", key));
                } else {
                    formParams.add(new BasicNameValuePair(key, value.toString()));
                }
            }
        }

        // 3. 创建 UrlEncodedFormEntity 对象并设置编码
        HttpEntity httpEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);

        try {
            httpPost.setEntity(httpEntity);
        } catch (Exception e) {
            ElgLogger.error(log, l -> l.error("HttpPost构建失败 URL: {}", httpPost.getURI(), e));
//            log.error("HttpPost构建失败 URL: {}", httpPost.getURI(), e);
            throw new RuntimeException("HttpPost构建异常: " + e.getMessage(), e);
        }
        return sendHttpPost(httpPost);
    }

    public static void main(String[] args) throws IOException {
        String reqUrl = "https://test-bh-xm.okap.com/authorize/api/req/rfa";
        //{"APPID":"4bef94c12e5c4a8b98490631bb675b92","APPLY_ID":"82acff020d114a41b937bc9881fbb2fc","FILEMD5":"11FD45103F1A3B2273C6744478E3D7AA","FILE":"/mnt/dzbh/test/resource/ofd/C05921909180769797005314/C05921909180769797005314Apply.pdf","TIMESTAMP":"20250407174541","SIGNATURE":"7D38CE58B73C1DA0E99713C5AC772C76"}
        //{"APPID":"4bef94c12e5c4a8b98490631bb675b92","APPLY_ID":"782a152b34844b7cb8b741328db915af","FILEMD5":"66F8500498A6AD7A097F9ECCCEF68E3E","FILE":"/mnt/dzbh/test/resource/ofd/C05921909547454160732161/C05921909547454160732161Apply.pdf","TIMESTAMP":"20250408180247","SIGNATURE":"3147AB40C557E12CA0187E38B78C6A5D"}
        Map<String, Object> params = new HashMap<>();
        params.put("APPID", "4bef94c12e5c4a8b98490631bb675b92");
        params.put("APPLY_ID", "782a152b34844b7cb8b741328db915af");
        params.put("FILEMD5", "66F8500498A6AD7A097F9ECCCEF68E3E");
        params.put("FILE", new File("D:\\temporary\\C05921909547454160732161Apply.pdf"));
        params.put("TIMESTAMP", "20250408180247");
        params.put("SIGNATURE", "3147AB40C557E12CA0187E38B78C6A5D");
//        doPostFormData(reqUrl, params, "");
        String response = doPostFormData(reqUrl, params);

        XMBaseRespDTO xmBaseRespDTO = JSON.parseObject(response, XMBaseRespDTO.class);

        System.out.println(xmBaseRespDTO.toString());

//        // 1. 创建请求头
//        HttpHeaders headers = new HttpHeaders();
////        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
////        headers.set("Charset", "UTF-8");
////        headers.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
//
//        // 2. 构建请求体
//        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
//
//        // 添加文件部分
//        if (params.get("FILE") != null) {
////            FileSystemResource fileResource = new FileSystemResource(file);
//            body.add("FILE", params.get("FILE"));
//        }
//
//        // 添加普通表单参数
//        params.forEach((key, value) -> {
//            if (value != null) {
//                body.add(key, value.toString());
//            }
//        });
//
//        // 3. 创建请求实体
//        org.springframework.http.HttpEntity<MultiValueMap<String, Object>> requestEntity = new org.springframework.http.HttpEntity<>(body, headers);
//        RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
//        ResponseEntity<XMBaseRespDTO> responseEntity = null;
//        String errorResponse = "";
//        try {
//            responseEntity = restTemplate.exchange(reqUrl, HttpMethod.POST, requestEntity, XMBaseRespDTO.class);
////            responseEntity = restTemplate.postForEntity(reqUrl, requestEntity, String.class);
//        } catch (HttpServerErrorException e) {
//            HttpHeaders responseHeaders = e.getResponseHeaders();
//            System.out.println("Response Headers: " + e.getResponseHeaders());
//            System.out.println("Content-Type: " + responseHeaders.getContentType());
//            System.out.println("Body: " + e.getResponseBodyAsString());
//            // 捕获 5xx 错误，并获取响应体
//            errorResponse = e.getResponseBodyAsString();
//            // 方法 2：手动读取原始响应（更可靠）
//            errorResponse = new String(e.getResponseBodyAsByteArray());
//            XMBaseRespDTO xmBaseRespDTO = new XMBaseRespDTO();
//            responseEntity = new ResponseEntity<>(xmBaseRespDTO,e.getStatusCode());
//            System.out.println("Server Error (500): " + errorResponse);
//        }
//        System.out.println(responseEntity.getBody());
    }
}
